<script setup lang="ts">
import type {TableProps} from "ant-design-vue/lib";
import {
  ApiCreateMember,
  ApiDeleteMember, ApiFreezeMember,
  ApiGetMemberList,
  ApiIssueCard, ApiUnFreezeMember,
  ApiUpdateMember,
  ApiUpdateMemberVisaInfo
} from "~/api/member";
import type {MemberData, VisaAndPassportIssueData, CardIssueData} from "~/api/member";
import dayjs from "dayjs";
import type {UnwrapRef} from "vue";
import {Modal} from "ant-design-vue";
import axios from "axios";


definePageMeta({layout:"backend"})

const permissions = usePermissions()
const { t } = useI18n()
const paginate = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  search: "",
  position: ["bottomCenter"]
})

const model_edit_modal_visible = ref(false)
const visa_info_update_modal_visible = ref(false)
const card_issue_modal_visible = ref(false)
const table_data = ref([])
const current_model:UnwrapRef<MemberData> = reactive<MemberData>({
  name: '',
  member_id: null,
  phone_number: '',
  nationality: '',
  birthday: dayjs(),
  member_pic: undefined,
  passport_picture: undefined,
  visa_period: null,
  passport_period: null,
  gender: 1,
  passport_no: '',
  passport_sign_location: '',
  description: '',
  number: '',
  visa_issue_at: null,
  visa_expires_at: null,
  birthday_string: null,
  passport_issue_at: null,
  passport_expires_at: null
})

const current_card_model:UnwrapRef<CardIssueData> = reactive<CardIssueData>({
  member_id: null,
  number: '',
  card_no: ''
})

const model_form = ref()
const passport_update_form = ref()
const card_issue_form = ref()

function refresh(){
  ApiGetMemberList({
    page: paginate.current,
    search: paginate.search,
    limit: paginate.pageSize
  }).then((res)=>{
    paginate.total = res.data.total
    paginate.current = res.data.page
    paginate.pageSize = res.data.limit
    table_data.value = res.data.data
  })
}
refresh()

const on_table_changed : TableProps['onChange'] = (pagination, filters, sorter, extra) => {
  paginate.current = pagination.current;
  paginate.pageSize = pagination.pageSize
  refresh()
}

const on_edit_clicked = (record: MemberData = {
  member_id: null,
  name: '',
  number: '',
  description: '',
  nationality: '',
  passport_no: '',
  passport_sign_location: '',
  phone_number: '',
  gender: 1,
  member_pic: null,
  birthday: dayjs(),
  passport_picture: null,
  passport_period: [dayjs(), dayjs()],
  visa_period: [dayjs(), dayjs()],
  visa_issue_at: null,
  visa_expires_at: null,
  birthday_string: null,
  passport_issue_at: null,
  passport_expires_at: null
})=>{
  current_model.member_id = record.member_id
  current_model.name = record.name
  current_model.number = record.number
  current_model.description = record.description
  current_model.nationality = record.nationality
  current_model.passport_no = record.passport_no
  current_model.passport_sign_location = record.passport_sign_location
  current_model.phone_number = record.phone_number
  current_model.gender = record.gender
  current_model.member_pic = record.picture_path
  current_model.birthday = dayjs(record.birthday)
  current_model.passport_picture = record.passport_picture
  current_model.passport_period = record.passport_expires_at && record.passport_issue_at? [ dayjs(record.passport_issue_at), dayjs(record.passport_expires_at)]: [null, null]
  current_model.visa_period = record.visa_issue_at&&record.visa_expires_at?[dayjs(record.visa_issue_at), dayjs(record.visa_expires_at)]:[null, null]
}



const submitCreateOrUpdate = (value: MemberData)=>{
  model_form.value.validate().then(()=> {
    const call = current_model.member_id ? ApiUpdateMember : ApiCreateMember
    call(value).then(() => {
      model_edit_modal_visible.value = false
      refresh()
    })
  })
}


const submitPassportAndVisaData = (value: VisaAndPassportIssueData) => {
  passport_update_form.value.validate().then(()=>{
    ApiUpdateMemberVisaInfo(value).then(()=>{
      visa_info_update_modal_visible.value = false
      refresh();
    })
  })
}


const submitIssueCard = (value:CardIssueData) => {
  card_issue_form.value.validate().then(()=>{
    ApiIssueCard(value).then(()=>{
      card_issue_modal_visible.value = false
      refresh();
    })
  })
}

const getStatusText = (record: MemberData)=>{
  if(!record.status)
    return 'member.disabled'
  else if(!record.passport_expires_at || dayjs(record.passport_expires_at) < dayjs())
    return 'member.passport_expired'
  else if(!record.visa_expires_at || dayjs(record.visa_expires_at) < dayjs())
    return 'member.visa_expired'
  else return 'member.normal_status'
}

const import_loading = ref(false)
const onImportMemberData = ()=>{
  import_loading.value = true
  axios.get(import.meta.env.VITE_MEMBER_IMPORT_SERVER + "/yn/member", {params: {memberNo: current_model.passport_no}}).then(res=>{
    if(res.data.status_code != 0)
    {
      message.error(res.data.message)
      return
    }
    if(res.data.data === null){
      message.error(t("member.record_not_found"))
      return
    }

    if(res.data.data.born_time)
      current_model.birthday = dayjs(res.data.data.born_time)
    if(res.data.data.sex)
      current_model.gender = res.data.data.sex==="0"? 1:0
    if(res.data.data.english_name)
      current_model.name = res.data.data.english_name
    if(res.data.data.country)
      current_model.nationality = res.data.data.country
    if(res.data.data.picture_path){
      $fetch(res.data.data.picture_path).then(res=>{
        current_model.member_pic = res
      }).catch(reason => {})
    }

  }).catch(error=>{
  }).finally(()=>{
    import_loading.value = false
  })
}



</script>

<template>
  <div class="bg-white p-5 flex-col flex gap-5 overflow-auto">
    <div class="flex justify-center items-center gap-3">
      <div class="flex-1">
        <span class="text-4xl">{{ $t("sidebar.system.member")}}</span>
      </div>
      <a-button type="primary"  v-if="permissions? permissions['sys.create_member']:false" @click="on_edit_clicked(),model_edit_modal_visible = true">{{$t("member.create")}}</a-button>
      <a-input class="w-2/12" v-model:value="paginate.search"/>
      <a-button @click="refresh">{{$t("common.search")}}</a-button>
    </div>
    <div class="flex-1 flex p-2">
      <a-table sticky class="flex-1" :pagination="paginate" :data-source="table_data" @change="on_table_changed" size="middle"
               :row-class-name="(_record, index) => {
                 if(dayjs(_record.passport_expires_at + ' 23:59:59') < dayjs() || !_record.passport_expires_at || !_record.visa_expires_at || dayjs(_record.visa_expires_at+ ' 23:59:59') < dayjs()){
                   return 'bg-red-300 hover:bg-red-300';
                 }
                 return '';

               }"
      >
        <a-table-column :title="t('member.name')" data-index="name" :ellipsis="true" key="name" align="center"/>
        <a-table-column :title="t('member.number')" data-index="number" :ellipsis="true" key="number" align="center"/>
        <a-table-column :title="t('member.gender')" data-index="gender" :ellipsis="true" key="gender" align="center"/>
        <a-table-column :title="t('member.card_no')" data-index="card_no" :ellipsis="true" key="card_no" align="center"/>
        <a-table-column :title="t('member.status')" data-index="status" :ellipsis="true" key="status" align="center"/>
        <a-table-column v-if="permissions? permissions['sys.view_member_detail']:false" :title="t('member.passport_no')" data-index="passport_no" :ellipsis="true" key="passport_no" align="center"/>
        <a-table-column v-if="permissions? permissions['sys.view_member_detail']:false" :title="t('member.phone_number')" data-index="phone_number" :ellipsis="true" key="phone_number" align="center"/>
        <a-table-column :title="t('common.action')" data-index="action" :ellipsis="true" key="action" :width="164" align="center"/>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'gender'">
            {{ record.gender? '男': "女"}}
          </template>
          <template v-if="column.key === 'status'">
            {{ $t(getStatusText(record))}}
          </template>
          <template v-if="column.key === 'action'">
            <div class="flex gap-x-1.5">
              <a-tooltip>
                <template #title>{{$t("member.update")}}</template>
                <edit-outlined v-if="permissions? permissions['sys.update_member']:false" @click="on_edit_clicked(record), model_edit_modal_visible = true" class="text-2xl text-green-600 cursor-pointer"/>
              </a-tooltip>
              <a-tooltip>
                <template #title>{{$t("member.update_passport_visa_data")}}</template>
                <idcard-outlined v-if="permissions? permissions['sys.attach_member_cards']:false" @click="on_edit_clicked(record), visa_info_update_modal_visible = true" class="text-2xl text-green-600 cursor-pointer"/>
              </a-tooltip>
              <a-tooltip>
                <template #title>{{$t("member.issue_card")}}</template>
                <credit-card-outlined v-if="permissions? permissions['sys.attach_member_cards']:false" @click="()=>{
                  current_card_model.card_no = ''
                  current_card_model.member_id = record.member_id
                  current_card_model.number = record.number
                  card_issue_modal_visible = true
                }" class="text-2xl text-green-600 cursor-pointer"/>
              </a-tooltip>
              <a-tooltip v-if="record.status">
                <template #title>{{$t("member.disable")}}</template>
                <minus-circle-outlined v-if="permissions? permissions['sys.freeze_member_card']:false" @click="()=>{
                  Modal.confirm({
                    title: $t('common.warning'),
                    content: $t('member.freeze_confirmation', {member_name: record.name}),
                    onOk: ()=>{
                      ApiFreezeMember(record.member_id).then(()=>{
                        refresh();
                      })
                    }
                  })
                }" class="text-2xl cursor-pointer text-yellow-400"/>
              </a-tooltip>
              <a-tooltip v-if="!record.status">
                <template #title>{{$t("member.enable")}}</template>
                <check-circle-outlined v-if="permissions? permissions['sys.freeze_member_card']:false" @click="()=>{
                  Modal.confirm({
                    title: $t('common.warning'),
                    content: $t('member.unfreeze_confirmation', {member_name: record.name}),
                    onOk: ()=>{
                      ApiUnFreezeMember(record.member_id).then(()=>{
                        refresh();
                      })
                    }
                  })
                }" class="text-2xl cursor-pointer text-yellow-400"/>
              </a-tooltip>
              <a-tooltip>
                <template #title>{{$t("member.delete")}}</template>
                <delete-outlined v-if="permissions? permissions['sys.delete_member']:false" @click="()=>{
                  Modal.confirm({
                    title: $t('common.delete_confirmation_title'),
                    content: $t('member.delete_confirmation', {member_name: record.name}),
                    onOk: ()=>{
                      ApiDeleteMember(record.member_id).then(()=>{
                        refresh();
                      })
                    }
                  })
                }" class="text-2xl cursor-pointer text-red-600"/>
              </a-tooltip>

            </div>
          </template>
        </template>
      </a-table>
    </div>
  </div>

  <a-modal :title="$t(current_model?.member_id? 'member.update':'member.create')"
           :maskClosable="false"
           :open="model_edit_modal_visible" @ok="submitCreateOrUpdate(current_model)" @cancel="model_edit_modal_visible = false">
    <a-form :model="current_model" layout="vertical" ref="model_form">
      <a-form-item :hidden="true" name="member_id">
        <a-input v-model:value="current_model.member_id"/>
      </a-form-item>
      <a-form-item name="name" :label="$t('member.name')" :rules="[{ required: true, message: 'Please input your username!' }]">
        <a-input v-model:value="current_model.name"/>
      </a-form-item>
      <a-form-item name="passport_no" :label="$t('member.passport_no')" required>
        <a-input-search v-model:value="current_model.passport_no" @search="onImportMemberData" :loading="import_loading"/>

      </a-form-item>
      <a-form-item name="number" :label="$t('member.number')" :rules="[{ required: true, message: 'Please input your username!' }]">
        <a-input v-model:value="current_model.number"/>
      </a-form-item>
      <a-form-item name="nationality" :label="$t('member.nationality')" required>
        <a-input v-model:value="current_model.nationality"/>
      </a-form-item>
      <a-form-item name="birthday" :label="$t('member.birthday')" required>
        <a-date-picker v-model:value="current_model.birthday" class="w-full"/>
      </a-form-item>
      <a-form-item name="member_pic" :label="$t('member.photo')" required>
        <CameraView v-model:value="current_model.member_pic"/>
      </a-form-item>
      <a-form-item name="visa_period" :label="$t('member.visa_period')" required>
        <a-range-picker v-model:value="current_model.visa_period" class="w-full"/>
      </a-form-item>
      <a-form-item name="passport_sign_location" :label="$t('member.passport_sign_location')" required>
        <a-input v-model:value="current_model.passport_sign_location"/>
      </a-form-item>
      <a-form-item name="passport_period" :label="$t('member.passport_period')" required>
        <a-range-picker v-model:value="current_model.passport_period" class="w-full"/>
      </a-form-item>
      <a-form-item name="passport_picture" :label="$t('member.passport_picture')">
        <CameraView v-model:value="current_model.passport_picture"/>
      </a-form-item>
      <a-form-item name="gender" :label="$t('member.gender')" required>
        <a-radio-group v-model:value="current_model.gender" name="gender">
          <a-radio :value="1">{{$t('common.male')}}</a-radio>
          <a-radio :value="0">{{$t('common.female')}}</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item name="phone_number" :label="$t('member.phone_number')">
        <a-input v-model:value="current_model.phone_number"/>
      </a-form-item>
      <a-form-item name="description" :label="$t('member.description')">
        <a-input v-model:value="current_model.description"/>
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal :title="$t('member.update_passport_visa_data')"
           :maskClosable="false"
           :open="visa_info_update_modal_visible" @ok="submitPassportAndVisaData(current_model)" @cancel="visa_info_update_modal_visible = false">
    <a-form :model="current_model" layout="vertical" ref="passport_update_form">
      <a-form-item :hidden="true" name="member_id">
        <a-input v-model:value="current_model.member_id"/>
      </a-form-item>
      <a-form-item name="number" :label="$t('member.number')" :rules="[{ required: true, message: $t('member.number_required_message') }]">
        <a-input v-model:value="current_model.number"/>
      </a-form-item>
      <a-form-item name="visa_period" :label="$t('member.visa_period')" required>
        <a-range-picker v-model:value="current_model.visa_period" class="w-full"/>
      </a-form-item>
      <a-form-item name="passport_no" :label="$t('member.passport_no')" required>
        <a-input v-model:value="current_model.passport_no"/>
      </a-form-item>
      <a-form-item name="passport_sign_location" :label="$t('member.passport_sign_location')" required>
        <a-input v-model:value="current_model.passport_sign_location"/>
      </a-form-item>
      <a-form-item name="passport_period" :label="$t('member.passport_period')" required>
        <a-range-picker v-model:value="current_model.passport_period" class="w-full"/>
      </a-form-item>
      <a-form-item name="passport_picture" :label="$t('member.passport_picture')">
        <CameraView v-model:value="current_model.passport_picture"/>
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal :title="$t('member.sign_card')"
           :maskClosable="false"
           :open="card_issue_modal_visible" @ok="submitIssueCard(current_card_model)" @cancel="card_issue_modal_visible = false">
    <a-form :model="current_card_model" layout="vertical" ref="card_issue_form">
      <a-form-item :hidden="true" name="member_id">
        <a-input v-model:value="current_model.member_id"/>
      </a-form-item>
      <a-form-item name="number" :label="$t('member.number')" :rules="[{ required: true, message: 'Please input your username!' }]">
        <a-input v-model:value="current_card_model.number"/>
      </a-form-item>
      <a-form-item name="card_no" :label="$t('member.card_no')" :rules="[{ required: true, message: 'Please input your username!' }]">
        <a-input v-model:value="current_card_model.card_no"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped>
:deep(.ant-table-cell){
  text-wrap: nowrap;
  background-color: transparent !important;
}

</style>
